#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
任务监控页面模块
"""

import logging
from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
    QTabWidget, QFrame, QGridLayout, QLineEdit, QComboBox,
    QCheckBox, QSpinBox, QFileDialog, QMessageBox, QListWidget,
    QListWidgetItem, QTableWidget, QTableWidgetItem, QHeaderView,
    QTextEdit, QDialog, QFormLayout, QDialogButtonBox
)
from PyQt6.QtCore import Qt, QDateTime
from PyQt6.QtGui import QIcon, QColor
import time


class TaskDetailDialog(QDialog):
    """任务详情对话框"""
    
    def __init__(self, task_data, parent=None):
        super().__init__(parent)
        self.task_data = task_data
        self.setWindowTitle(f"任务详情: {task_data['name']}")
        self.resize(700, 500)
        self._setup_ui()
    
    def _setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        
        # 任务信息
        info_frame = QFrame()
        info_frame.setFrameShape(QFrame.Shape.StyledPanel)
        info_layout = QFormLayout(info_frame)
        
        # 任务名称
        info_layout.addRow("任务名称:", QLabel(self.task_data["name"]))
        
        # 触发器
        info_layout.addRow("触发器:", QLabel(self.task_data["trigger"]))
        
        # 脚本
        info_layout.addRow("执行脚本:", QLabel(self.task_data["script"]))
        
        # 状态
        status_label = QLabel(self.task_data["status"])
        status_color = {
            "运行中": "#2ecc71",
            "等待中": "#f39c12",
            "已完成": "#3498db",
            "失败": "#e74c3c"
        }.get(self.task_data["status"], "#7f8c8d")
        status_label.setStyleSheet(f"color: {status_color}; font-weight: bold;")
        info_layout.addRow("状态:", status_label)
        
        # 开始时间
        start_time = QDateTime.fromSecsSinceEpoch(self.task_data["start_time"]).toString("yyyy-MM-dd hh:mm:ss")
        info_layout.addRow("开始时间:", QLabel(start_time))
        
        # 结束时间
        if self.task_data.get("end_time"):
            end_time = QDateTime.fromSecsSinceEpoch(self.task_data["end_time"]).toString("yyyy-MM-dd hh:mm:ss")
            info_layout.addRow("结束时间:", QLabel(end_time))
        
        # 执行节点
        if self.task_data.get("node"):
            info_layout.addRow("执行节点:", QLabel(self.task_data["node"]))
        
        layout.addWidget(info_frame)
        
        # 执行日志
        log_label = QLabel("执行日志:")
        log_label.setStyleSheet("font-weight: bold;")
        layout.addWidget(log_label)
        
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        self.log_text.setPlainText(self.task_data.get("log", ""))
        layout.addWidget(self.log_text)
        
        # 按钮
        button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)


class TasksPage(QWidget):
    """任务监控页面"""
    
    def __init__(self, config, database=None, task_scheduler=None):
        super().__init__()
        self.config = config
        self.database = database
        self.task_scheduler = task_scheduler
        self.tasks = []  # 任务列表
        self._setup_ui()
        self._load_tasks()
        self._add_context_menu()  # 添加上下文菜单
        logging.info("任务监控页面已初始化")
    
    def _setup_ui(self):
        """设置UI"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        
        # 标题
        title_label = QLabel("任务监控")
        title_label.setStyleSheet("font-size: 24px; font-weight: bold;")
        main_layout.addWidget(title_label)
        
        # 标签页
        self.tabs = QTabWidget()
        
        # 活动任务标签页
        self.active_tab = QWidget()
        self._setup_active_tab()
        self.tabs.addTab(self.active_tab, "活动任务")
        
        # 历史任务标签页
        self.history_tab = QWidget()
        self._setup_history_tab()
        self.tabs.addTab(self.history_tab, "历史任务")
        
        main_layout.addWidget(self.tabs)
    
    def _setup_active_tab(self):
        """设置活动任务标签页"""
        layout = QVBoxLayout(self.active_tab)
        
        # 工具栏
        toolbar_layout = QHBoxLayout()
        
        # 刷新按钮
        refresh_btn = QPushButton("刷新")
        refresh_btn.clicked.connect(self._refresh_active_tasks)
        toolbar_layout.addWidget(refresh_btn)
        
        # 取消任务按钮
        cancel_btn = QPushButton("取消任务")
        cancel_btn.clicked.connect(self._cancel_task)
        toolbar_layout.addWidget(cancel_btn)
        
        toolbar_layout.addStretch()
        
        # 过滤选项
        toolbar_layout.addWidget(QLabel("状态:"))
        self.status_filter = QComboBox()
        self.status_filter.addItems(["全部", "运行中", "等待中"])
        self.status_filter.currentTextChanged.connect(self._filter_active_tasks)
        toolbar_layout.addWidget(self.status_filter)
        
        # 搜索框
        toolbar_layout.addWidget(QLabel("搜索:"))
        self.active_search_edit = QLineEdit()
        self.active_search_edit.setPlaceholderText("输入关键字搜索任务")
        self.active_search_edit.textChanged.connect(self._filter_active_tasks)
        toolbar_layout.addWidget(self.active_search_edit)
        
        layout.addLayout(toolbar_layout)
        
        # 任务表格
        self.active_table = QTableWidget()
        self.active_table.setColumnCount(6)
        self.active_table.setHorizontalHeaderLabels(["ID", "名称", "触发器", "脚本", "状态", "开始时间"])
        self.active_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
        self.active_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
        self.active_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
        self.active_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch)
        self.active_table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents)
        self.active_table.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeMode.ResizeToContents)
        self.active_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.active_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        self.active_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.active_table.itemDoubleClicked.connect(self._show_task_detail)
        
        layout.addWidget(self.active_table)
    
    def _setup_history_tab(self):
        """设置历史任务标签页"""
        layout = QVBoxLayout(self.history_tab)
        
        # 工具栏
        toolbar_layout = QHBoxLayout()
        
        # 刷新按钮
        refresh_btn = QPushButton("刷新")
        refresh_btn.clicked.connect(self._refresh_history_tasks)
        toolbar_layout.addWidget(refresh_btn)
        
        # 清空历史按钮
        clear_btn = QPushButton("清空历史")
        clear_btn.clicked.connect(self._clear_history)
        toolbar_layout.addWidget(clear_btn)
        
        toolbar_layout.addStretch()
        
        # 过滤选项
        toolbar_layout.addWidget(QLabel("状态:"))
        self.history_status_filter = QComboBox()
        self.history_status_filter.addItems(["全部", "已完成", "失败"])
        self.history_status_filter.currentTextChanged.connect(self._filter_history_tasks)
        toolbar_layout.addWidget(self.history_status_filter)
        
        # 搜索框
        toolbar_layout.addWidget(QLabel("搜索:"))
        self.history_search_edit = QLineEdit()
        self.history_search_edit.setPlaceholderText("输入关键字搜索任务")
        self.history_search_edit.textChanged.connect(self._filter_history_tasks)
        toolbar_layout.addWidget(self.history_search_edit)
        
        layout.addLayout(toolbar_layout)
        
        # 任务表格
        self.history_table = QTableWidget()
        self.history_table.setColumnCount(7)
        self.history_table.setHorizontalHeaderLabels(["ID", "名称", "触发器", "脚本", "状态", "开始时间", "结束时间"])
        self.history_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
        self.history_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
        self.history_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
        self.history_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch)
        self.history_table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents)
        self.history_table.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeMode.ResizeToContents)
        self.history_table.horizontalHeader().setSectionResizeMode(6, QHeaderView.ResizeMode.ResizeToContents)
        self.history_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.history_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        self.history_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.history_table.itemDoubleClicked.connect(self._show_task_detail)
        
        layout.addWidget(self.history_table)
    
    def _load_tasks(self):
        """加载任务列表"""
        # 这里应该从数据库加载任务列表
        # 目前使用模拟数据
        current_time = int(time.time())
        
        self.tasks = [
            {
                "id": 1,
                "name": "每日数据爬取",
                "trigger": "每日报表",
                "script": "网页爬虫示例",
                "status": "运行中",
                "start_time": current_time - 300,
                "node": "主节点",
                "log": "正在爬取数据...\n已完成30%\n"
            },
            {
                "id": 2,
                "name": "文件处理任务",
                "trigger": "新文件监控",
                "script": "桌面自动化示例",
                "status": "等待中",
                "start_time": current_time - 600,
                "node": "主节点",
                "log": "等待资源分配...\n"
            },
            {
                "id": 3,
                "name": "数据分析报告",
                "trigger": "每日报表",
                "script": "网页爬虫示例",
                "status": "已完成",
                "start_time": current_time - 86400,
                "end_time": current_time - 86100,
                "node": "主节点",
                "log": "开始分析数据...\n数据处理完成\n生成报告...\n任务完成\n"
            },
            {
                "id": 4,
                "name": "系统备份",
                "trigger": "每周备份",
                "script": "备份脚本",
                "status": "失败",
                "start_time": current_time - 43200,
                "end_time": current_time - 43000,
                "node": "备份节点",
                "log": "开始备份...\n连接存储服务器...\n错误: 无法连接到存储服务器\n任务失败\n"
            },
        ]
        
        self._update_task_tables()
    
    def _update_task_tables(self):
        """更新任务表格"""
        # 清空表格
        self.active_table.setRowCount(0)
        self.history_table.setRowCount(0)
        
        # 填充活动任务表格
        for task in self.tasks:
            if task["status"] in ["运行中", "等待中"]:
                self._add_task_to_active_table(task)
            else:
                self._add_task_to_history_table(task)
    
    def _add_task_to_active_table(self, task):
        """添加任务到活动表格"""
        row = self.active_table.rowCount()
        self.active_table.insertRow(row)
        
        self.active_table.setItem(row, 0, QTableWidgetItem(str(task["id"])))
        self.active_table.setItem(row, 1, QTableWidgetItem(task["name"]))
        self.active_table.setItem(row, 2, QTableWidgetItem(task["trigger"]))
        self.active_table.setItem(row, 3, QTableWidgetItem(task["script"]))
        
        status_item = QTableWidgetItem(task["status"])
        status_color = "#2ecc71" if task["status"] == "运行中" else "#f39c12"
        status_item.setForeground(QColor(status_color))
        self.active_table.setItem(row, 4, status_item)
        
        start_time = QDateTime.fromSecsSinceEpoch(task["start_time"]).toString("yyyy-MM-dd hh:mm:ss")
        self.active_table.setItem(row, 5, QTableWidgetItem(start_time))
    
    def _add_task_to_history_table(self, task):
        """添加任务到历史表格"""
        row = self.history_table.rowCount()
        self.history_table.insertRow(row)
        
        self.history_table.setItem(row, 0, QTableWidgetItem(str(task["id"])))
        self.history_table.setItem(row, 1, QTableWidgetItem(task["name"]))
        self.history_table.setItem(row, 2, QTableWidgetItem(task["trigger"]))
        self.history_table.setItem(row, 3, QTableWidgetItem(task["script"]))
        
        status_item = QTableWidgetItem(task["status"])
        status_color = "#3498db" if task["status"] == "已完成" else "#e74c3c"
        status_item.setForeground(QColor(status_color))
        self.history_table.setItem(row, 4, status_item)
        
        start_time = QDateTime.fromSecsSinceEpoch(task["start_time"]).toString("yyyy-MM-dd hh:mm:ss")
        self.history_table.setItem(row, 5, QTableWidgetItem(start_time))
        
        if task.get("end_time"):
            end_time = QDateTime.fromSecsSinceEpoch(task["end_time"]).toString("yyyy-MM-dd hh:mm:ss")
            self.history_table.setItem(row, 6, QTableWidgetItem(end_time))
    
    def _filter_active_tasks(self):
        """筛选活动任务"""
        status = self.status_filter.currentText()
        search_text = self.active_search_edit.text().lower()
        
        self.active_table.setRowCount(0)
        
        for task in self.tasks:
            # 检查状态筛选
            if status != "全部" and task["status"] != status:
                continue
            
            # 只显示活动任务
            if task["status"] not in ["运行中", "等待中"]:
                continue
            
            # 检查搜索文本
            if search_text and search_text not in task["name"].lower() and search_text not in task["trigger"].lower() and search_text not in task["script"].lower():
                continue
            
            self._add_task_to_active_table(task)
    
    def _filter_history_tasks(self):
        """筛选历史任务"""
        status = self.history_status_filter.currentText()
        search_text = self.history_search_edit.text().lower()
        
        self.history_table.setRowCount(0)
        
        for task in self.tasks:
            # 检查状态筛选
            if status != "全部":
                if status == "已完成" and task["status"] != "已完成":
                    continue
                if status == "失败" and task["status"] != "失败":
                    continue
            
            # 只显示历史任务
            if task["status"] in ["运行中", "等待中"]:
                continue
            
            # 检查搜索文本
            if search_text and search_text not in task["name"].lower() and search_text not in task["trigger"].lower() and search_text not in task["script"].lower():
                continue
            
            self._add_task_to_history_table(task)
    
    def _refresh_active_tasks(self):
        """刷新活动任务"""
        # 这里应该从后端获取最新的活动任务
        # 目前只是重新加载现有数据
        self._filter_active_tasks()
        logging.info("已刷新活动任务列表")
    
    def _refresh_history_tasks(self):
        """刷新历史任务"""
        # 这里应该从后端获取最新的历史任务
        # 目前只是重新加载现有数据
        self._filter_history_tasks()
        logging.info("已刷新历史任务列表")
    
    def _cancel_task(self):
        """取消任务"""
        current_row = self.active_table.currentRow()
        if current_row >= 0:
            task_id = int(self.active_table.item(current_row, 0).text())
            
            # 查找对应的任务
            for task in self.tasks:
                if task["id"] == task_id:
                    reply = QMessageBox.question(
                        self, "确认取消", f"确定要取消任务 '{task['name']}' 吗？",
                        QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                        QMessageBox.StandardButton.No
                    )
                    
                    if reply == QMessageBox.StandardButton.Yes:
                        # 这里应该调用后端API取消任务
                        # 目前只是修改状态
                        task["status"] = "已取消"
                        task["end_time"] = int(time.time())
                        self._update_task_tables()
                        logging.info(f"已取消任务: {task['name']}")
                    break
    
    def _clear_history(self):
        """清空历史任务"""
        reply = QMessageBox.question(
            self, "确认清空", "确定要清空所有历史任务记录吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            # 这里应该调用后端API清空历史任务
            # 目前只是移除非活动任务
            self.tasks = [task for task in self.tasks if task["status"] in ["运行中", "等待中"]]
            self._update_task_tables()
            logging.info("已清空历史任务记录")
    
    def _show_task_detail(self, item):
        """显示任务详情"""
        table = self.sender()
        current_row = table.currentRow()
        
        if current_row >= 0:
            task_id = int(table.item(current_row, 0).text())
            
            # 查找任务数据
            for task in self.tasks:
                if task["id"] == task_id:
                    dialog = TaskDetailDialog(task, parent=self)
                    dialog.exec()
                    break

    def _add_context_menu(self):
        """添加上下文菜单"""
        # 为活动任务表格添加上下文菜单
        self.active_table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.active_table.customContextMenuRequested.connect(self._show_active_context_menu)
        
        # 为历史任务表格添加上下文菜单
        self.history_table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.history_table.customContextMenuRequested.connect(self._show_history_context_menu)

    def _show_active_context_menu(self, position):
        """显示活动任务上下文菜单"""
        current_row = self.active_table.currentRow()
        if current_row < 0:
            return
            
        menu = QMenu(self)
        
        # 查看详情
        detail_action = QAction("查看详情", self)
        detail_action.triggered.connect(lambda: self._show_task_detail(None))
        menu.addAction(detail_action)
        
        # 取消任务
        cancel_action = QAction("取消任务", self)
        cancel_action.triggered.connect(self._cancel_task)
        menu.addAction(cancel_action)
        
        # 跳转到触发器
        trigger_name = self.active_table.item(current_row, 2).text()
        goto_trigger_action = QAction(f"跳转到触发器: {trigger_name}", self)
        goto_trigger_action.triggered.connect(lambda: self._goto_trigger(trigger_name))
        menu.addAction(goto_trigger_action)
        
        # 跳转到脚本
        script_name = self.active_table.item(current_row, 3).text()
        goto_script_action = QAction(f"跳转到脚本: {script_name}", self)
        goto_script_action.triggered.connect(lambda: self._goto_script(script_name))
        menu.addAction(goto_script_action)
        
        menu.exec(self.active_table.mapToGlobal(position))

    def _show_history_context_menu(self, position):
        """显示历史任务上下文菜单"""
        current_row = self.history_table.currentRow()
        if current_row < 0:
            return
            
        menu = QMenu(self)
        
        # 查看详情
        detail_action = QAction("查看详情", self)
        detail_action.triggered.connect(lambda: self._show_task_detail(None))
        menu.addAction(detail_action)
        
        # 跳转到触发器
        trigger_name = self.history_table.item(current_row, 2).text()
        goto_trigger_action = QAction(f"跳转到触发器: {trigger_name}", self)
        goto_trigger_action.triggered.connect(lambda: self._goto_trigger(trigger_name))
        menu.addAction(goto_trigger_action)
        
        # 跳转到脚本
        script_name = self.history_table.item(current_row, 3).text()
        goto_script_action = QAction(f"跳转到脚本: {script_name}", self)
        goto_script_action.triggered.connect(lambda: self._goto_script(script_name))
        menu.addAction(goto_script_action)
        
        menu.exec(self.history_table.mapToGlobal(position))

    def _goto_trigger(self, trigger_name):
        """跳转到触发器页面"""
        # 切换到触发器页面
        main_window = self.window()
        main_window.tabs.setCurrentIndex(1)  # 触发器页面的索引
        logging.info(f"跳转到触发器: {trigger_name}")

    def _goto_script(self, script_name):
        """跳转到脚本页面"""
        # 切换到脚本页面
        main_window = self.window()
        main_window.tabs.setCurrentIndex(2)  # 脚本页面的索引
        logging.info(f"跳转到脚本: {script_name}")